/**
 *
 */
package 算法;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 *
 *
 * @Title:
 * @author zhoujie
 * @date 2018年6月4日 下午6:12:32
 *
 */
public class FindArrayMostElements {
    public static void main(String[] args) {
        findArrayMostElements2(Arrays.asList("1", "2", "2", "2", "1", "a", "a", "a", "a", "c", "d"));
    }

    /**
     * 查找数组中最多的元素
     * @param list
     */
    public static void findArrayMostElements2(List<String> list) {
        Entry<String, Long> e = list.stream()
                .collect(Collectors.toMap(Function.identity(), v -> 1L, (v1, v2) -> v1 + 1))
                .entrySet().stream().max((v1, v2) -> v1.getValue().compareTo(v2.getValue())).get();
        System.out.println("出现最多的元素为：" + e.getKey() + "  次数为：" + e.getValue());
    }

    public static String findArrayMostElements(List<String> list) {
        Map<String, Long> numMap = new HashMap<>(list.size());
        list.stream().forEachOrdered(s -> numMap.put(s, Objects.isNull(numMap.get(s)) ? 0L : numMap.get(s) + 1));

        Long[] maxNum = {null};
        String[] maxKey = {null};
        numMap.forEach((k, v) -> {
            if (Objects.isNull(maxKey[0]) || v > maxNum[0]) {
                maxKey[0] = k;
                maxNum[0] = v;
            }
        });
        return maxKey[0];
    }


}
